package org.siqisource.webstart.core.utils.pagination;

public class OracleDialect extends Dialect {

	private static final String FOR_UPDATE = " for update";

	private static final int EXTEND_LENGTH = 100;

	@Override
	public String getLimitString(String sql, int offset, int limit) {

		sql = sql.trim();
		boolean isForUpdate = false;
		if (sql.toLowerCase().endsWith(FOR_UPDATE)) {
			sql = sql.substring(0, sql.length() - FOR_UPDATE.length());
			isForUpdate = true;
		}

		StringBuffer pagingSelect = new StringBuffer(sql.length() + EXTEND_LENGTH);

		pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( ");

		pagingSelect.append(sql);

		pagingSelect.append(" ) row_ ) where rownum_ > " + offset + " and rownum_ <= " + (offset + limit));

		if (isForUpdate) {
			pagingSelect.append(" for update");
		}

		return pagingSelect.toString();
	}
}
